package cn.wen.eeayjoke.ui.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;

import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import cn.wen.base.adapter.recyclerview.QuickRecyclerViewHolder;
import cn.wen.base.adapter.recyclerview.QuickVAdapter;
import cn.wen.base.util.DensityUtils;
import cn.wen.base.vlayout.DelegateAdapter;
import cn.wen.base.vlayout.VirtualLayoutManager;
import cn.wen.base.vlayout.layout.GridLayoutHelper;
import cn.wen.core.titlebar.TitleBarUtil;
import cn.wen.core.ui.AppFragment;
import cn.wen.eeayjoke.R;
import cn.wen.eeayjoke.adapter.home.HomeAdapterManager;
import cn.wen.eeayjoke.entity.bean.home.HomeData;
import cn.wen.eeayjoke.entity.bean.home.MoreBean;
import cn.wen.eeayjoke.entity.bean.home.MoreItem;
import cn.wen.eeayjoke.presenter.HomePresenter;
import cn.wen.eeayjoke.presenter.observer.QuickObserver;
import cn.wen.eeayjoke.refresh.AppRefreshLayout;
import cn.wen.eeayjoke.utils.ItemTypes;
import cn.wen.eeayjoke.view.HomeTitleHolder;

/**
 * 首页
 */

public class HomeFmt extends AppFragment {
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.refresh_layout)
    AppRefreshLayout mRefreshLayout;
    @BindView(R.id.fl_home_title)
    FrameLayout mFLTitleContent;
    private HomePresenter mPresenter;
    private List<DelegateAdapter.Adapter> mAdapters = new LinkedList<>();
    private DelegateAdapter mAdapter;
    private VirtualLayoutManager mLayoutManager;
    private HomeAdapterManager mAdapterManager;

    private String nextPage = "1";
    private boolean hasNextPage = false;
    private int mDistance;


    @Override
    protected Object getContentLayout() {
        return R.layout.fmt_home;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mPresenter = new HomePresenter();
        mAdapterManager = new HomeAdapterManager();
    }

    @Override
    protected void initView(View contentView) {
        // 设置
        setRecyclerData();
        // 下拉刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                requestData();
            }
        });
        // 加载更多
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                loadMore();
            }
        });
        // 初始化Title
        final HomeTitleHolder holder = new HomeTitleHolder(getAppActivity(), mFLTitleContent);
        mFLTitleContent.addView(holder.getRootView());
        TitleBarUtil.setTitlePadding(getAppActivity(), holder.getFLTitleRoot());
        mDistance = DensityUtils.dp2px(getAppActivity(), 190);

        mRecyclerView.setItemViewCacheSize(50);
        mRecyclerView.setDrawingCacheEnabled(true);
        mRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);


        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int scrollState) {

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int i, int i2) {
                int offset = mLayoutManager.getOffsetToStart();
                float alpha = offset * 1.0f / mDistance;
                holder.change(alpha);
            }
        });
        // 下拉监听
        mRefreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onHeaderPulling(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {
                holder.getRootView().setVisibility(View.GONE);
            }

            @Override
            public void onHeaderFinish(RefreshHeader header, boolean success) {
                holder.getRootView().setVisibility(View.VISIBLE);
            }

            @Override
            public void onStateChanged(RefreshLayout refreshLayout, RefreshState oldState, RefreshState newState) {
                switch (newState) {
                    case None:
                        holder.getRootView().setVisibility(View.VISIBLE);
                        break;
                }
            }
        });
        mRefreshLayout.autoRefresh();
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        if (!hasNextPage) {
            mRefreshLayout.setEnableLoadMore(hasNextPage);
            return;
        }
        mPresenter.moreAlsoLike(nextPage, new QuickObserver<MoreBean>(getAppActivity()) {
            @Override
            public void onResponse(MoreBean data) {
                setLoadMore(data);
            }

            @Override
            public void onComplete() {
                mRefreshLayout.finishLoadMore();
            }
        });
    }

    @Override
    protected void initNet() {
        requestData();
    }

    /**
     * 加载首页数据
     */
    private void setRecyclerData() {
        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mRecyclerView.setRecycledViewPool(viewPool);
        // 1. 设置LayoutManager
        mLayoutManager = new VirtualLayoutManager(getAppActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        // 这个是包装的Adapter
        mAdapter = new DelegateAdapter(mLayoutManager, true);
        mAdapter.addAdapters(mAdapters);
        mRecyclerView.setAdapter(mAdapter);

        Handler handler = new Handler();
        handler.sendMessage(Message.obtain());
    }

    /**
     * 请求数据
     */
    private void requestData() {
        mPresenter.index(new QuickObserver<HomeData>(getAppActivity()) {
            @Override
            public void onResponse(HomeData data) {
                setHomeData(data);
            }

            @Override
            public void onComplete() {
                mRefreshLayout.finishRefresh();
            }
        });
    }

    private void setHomeData(HomeData data) {
        hasNextPage = true;
        nextPage = "1";
        mAdapters.clear();
        mAdapter.clear();
        mAdapters.addAll(mAdapterManager.getAdapters(data));
        mAdapter.addAdapters(mAdapters);
        mAdapter.notifyDataSetChanged();
        mRefreshLayout.setEnableLoadMore(hasNextPage);
    }


    public void setLoadMore(MoreBean data) {
        nextPage = data.nextPage;
        hasNextPage = data.hasNextPage;
        // TODO
        List<MoreItem> items = data.items;
        GridLayoutHelper helper = new GridLayoutHelper(2);
        QuickVAdapter<MoreItem> moreAdapter = new QuickVAdapter<MoreItem>(items, helper, R.layout.main_meal) {
            @Override
            protected void convert(QuickRecyclerViewHolder holder, MoreItem detail, int position) {
                holder.displayImage(R.id.iv_icon, detail.goodsThumb, R.drawable.transparent);
                holder.displayImage(R.id.iv_hot, detail.activityIcon, R.drawable.transparent);
                holder.setText(R.id.tv_sell_count, "销量:" + detail.favoriteCount);
                String price = "¥" + detail.supplyPrice;
                holder.setText(R.id.tv_price, price);
                holder.setText(R.id.tv_desc, detail.goodsName);
            }

            @Override
            public int getItemViewType(int position) {
                return ItemTypes.TYPE_ITEM;
            }
        };
        mAdapter.addAdapter(moreAdapter);
        mAdapter.notifyDataSetChanged();
    }
}
